﻿using Domain.Entitys.FG;
using Domain.Entitys.Sinv;
using Domain.IRepositorys.Sinv;
using Microsoft.EntityFrameworkCore;
using System.Reflection.Emit;
using static Domain.Entitys.FG.FG_Finished_Goods_Store_Info;
using static Domain.Entitys.Pinv.Po_details_Order;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EFCore.Repositorys.Sinv
{
    public class Sinv_Sale_OutboundRepository : ISinv_Sale_OutboundRepository
    {
        private readonly MyDbContext myDbContext;

        public Sinv_Sale_OutboundRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 根据销售出库编号查询对应销售出库信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<Sinv_Sale_Outbound> GetSinv_Sale_OutboundByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Outbound.FirstOrDefaultAsync(so => so.Sale_outbound_code == code);
        }

        /// <summary>
        /// 根据销售出库编号查询销售出库明细
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Outbound_Details>> GetSinv_Sale_Outbound_DetailsByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Outbound_Details.Where(sod => sod.Sale_outbound_code == code).ToListAsync();
        }

        /// <summary>
        /// 分页条件查询销售出库信息及其明细
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public List<Sinv_Sale_Outbound_Info> GetSinv_Sale_Outbound_Infos(int currentPage, int pageSize, string customerName, string orderCode, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Outbound> query = myDbContext.Sinv_Sale_Outbound;
            query = query.Where(so => so.Del_flag == '0').OrderByDescending(so => so.Create_time).ThenByDescending(so => so.Update_time);

            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(so => so.Customer_code.Contains(customerName) || so.Customer_name.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(so => so.Sale_order_code.Contains(orderCode));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_outbound_status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_outbound_audit_status == auditStatus);
            }
            if (currentPage != 0 && pageSize != 0)
            {
                query = query.Skip((currentPage - 1) * pageSize).Take(pageSize);
            }
            var result = query
                //.ThenBy(so => so.Create_time)
                .Select(so => new Sinv_Sale_Outbound_Info
                {
                    Sale_outbound_id = so.Sale_outbound_id,
                    Sale_outbound_code = so.Sale_outbound_code,
                    Sale_order_name = so.Sale_order_name,
                    Sale_order_code = so.Sale_order_code,
                    Customer_name = so.Customer_name,
                    Customer_code = so.Customer_code,
                    Contacts_name = so.Contacts_name,
                    Contacts_phone = so.Contacts_phone,
                    Sale_order_rep_id = so.Sale_order_rep_id,
                    Sale_order_dept_id = so.Sale_order_dept_id,
                    Sale_outbound_rep_id = so.Sale_outbound_rep_id,
                    Sale_outbound_status = so.Sale_outbound_status,
                    Sale_outbound_time = so.Sale_outbound_time,
                    Sale_outbound_dept_id = so.Sale_outbound_dept_id,
                    Warehouse_code = so.Warehouse_code,
                    Zone_code = so.Zone_code,
                    Sale_outbound_audit_status = so.Sale_outbound_audit_status,
                    Warehouse_name = so.Warehouse_name,
                    Zone_name = so.Warehouse_name,
                    Details = so.Details.Select(details => new Sinv_Sale_Outbound_Info.Sinv_Sale_Outbound_Details
                    {
                        Sale_outbound_details_id = details.Sale_outbound_details_id,
                        Sale_outbound_id = details.Sale_outbound_id,
                        Sale_outbound_code = details.Sale_outbound_code,
                        Pro_name = details.Pro_name,
                        Pro_code = details.Pro_code,
                        Pro_brand = details.Pro_brand,
                        Pro_model = details.Pro_model,
                        Measure_id = details.Measure_id,
                        Pro_sale_qty = details.Pro_sale_qty,
                        Pro_awaiting_dispatch_qty = details.Pro_awaiting_dispatch_qty,
                        Pro_current_shipment_qty = details.Pro_current_shipment_qty
                    }).ToList()
                }).ToList();
            return result;
        }

        /// <summary>
        /// 添加销售出库信息及其详情
        /// </summary>
        /// <param name="sinv_Sale_Outbound">销售出库信息</param>
        /// <param name="sinv_Sale_Outbound_Details">详情信息</param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OutboundAddAsync(
            Sinv_Sale_Outbound sinv_Sale_Outbound,
            List<Sinv_Sale_Outbound_Details> sinv_Sale_Outbound_Details)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();

            try
            {
                // 1. 先保存出库主表
                await myDbContext.AddAsync(sinv_Sale_Outbound);
                await myDbContext.SaveChangesAsync();

                // 2. 保存出库明细
                foreach (var detail in sinv_Sale_Outbound_Details)
                {
                    detail.Sale_outbound_id = sinv_Sale_Outbound.Sale_outbound_id;
                    detail.Sale_outbound_code = sinv_Sale_Outbound.Sale_outbound_code;
                }
                await myDbContext.AddRangeAsync(sinv_Sale_Outbound_Details);
                await myDbContext.SaveChangesAsync();

                //3.更新订单状态
                //var order = await myDbContext.Sinv_Sale_Order
                //    .FirstAsync(so => so.Sale_order_code == sinv_Sale_Outbound.Sale_order_code);
                //order.Sale_order_status = sinv_Sale_Outbound.Sale_outbound_status;

                //4.计算累计出库量（包含本次）
                var orderDetails = await myDbContext.Sinv_Sale_Order_Details
                    .Where(sod => sod.Sale_order_code == sinv_Sale_Outbound.Sale_order_code)
                    .ToListAsync();
                //var proCodes = sinv_Sale_Outbound_Details.Select(d => d.Pro_code).Distinct().ToList();
                //var locationCodes = sinv_Sale_Outbound_Details.Select(d => d.Location_code).Distinct().ToList();
                //var stockList = await myDbContext.inv_stock
                //    .Where(s => proCodes.Contains(s.pro_code)
                //    && locationCodes.Contains(s.Location_Code)
                //        && sinv_Sale_Outbound.Warehouse_code.Contains(s.Warehouse_Code)
                //        && sinv_Sale_Outbound.Zone_code.Contains(s.Zone_Code))
                //    .ToListAsync();

                foreach (var item in orderDetails)
                {
                    // 预计出库量（从入参明细中获取）
                    var currentOutQty = sinv_Sale_Outbound_Details
                        .Where(d => d.Sale_order_details_id == item.Sale_order_details_id)
                        .Sum(d => d.Pro_current_shipment_qty);

                    // 历史+本次出库量
                    item.Pro_planned_outbound_qty += currentOutQty;
                }
                //// 字典1：以stock_id为键
                //var stocksById = stockList.ToDictionary(s => s.stock_id);
                //// 字典2：以pro_code为键映射到stock_id
                //var stockIdByProCode = stockList.ToDictionary(s => s.pro_code, s => s.stock_id);

                //foreach (var item in sinv_Sale_Outbound_Details)
                //{
                //    if (stockIdByProCode.TryGetValue(item.Pro_code, out var stockId))
                //    {
                //        stocksById[stockId].Stock_planned_outbound_qty += item.Pro_current_shipment_qty;
                //        myDbContext.Entry(stocksById[stockId]).State = EntityState.Modified;
                //    }
                //}


                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 修改销售出库信息审核状态，减少商品库存，增加销售明细出库数量，修改销售订单出库状态
        /// </summary>
        /// <param name="sinv_Sale_Outbound"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OutboundAuditUpdateAsync(Sinv_Sale_Outbound sinv_Sale_Outbound)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售出库信息审核状态
                Sinv_Sale_Outbound sale_Outbound = await myDbContext.Sinv_Sale_Outbound
                    .FirstOrDefaultAsync(so => so.Sale_outbound_id == sinv_Sale_Outbound.Sale_outbound_id);
                sale_Outbound.Sale_outbound_audit_by = sinv_Sale_Outbound.Sale_outbound_audit_by;
                sale_Outbound.Sale_outbound_audit_time = sinv_Sale_Outbound.Sale_outbound_audit_time;
                sale_Outbound.Sale_outbound_audit_status = sinv_Sale_Outbound.Sale_outbound_audit_status;
                sale_Outbound.Sale_outbound_audit_opinion = sinv_Sale_Outbound.Sale_outbound_audit_opinion;
                myDbContext.Update(sale_Outbound);

                //更新销售明细预计出库数量
                List<Sinv_Sale_Outbound_Details> sinv_Sale_Outbound_Details = await myDbContext.Sinv_Sale_Outbound_Details
                    .Where(sod => sod.Sale_outbound_id == sinv_Sale_Outbound.Sale_outbound_id).ToListAsync();

                if (sale_Outbound.Sale_outbound_audit_status == '1')//审核状态 = 通过 减少库存、增加出库数量、改变订单状态
                {
                    await UpdateInventoryAndOrdersAsync(sale_Outbound, sinv_Sale_Outbound_Details);
                }
                else if (sale_Outbound.Sale_outbound_audit_status == '2')//审核状态 = 驳回减少预计出库数量
                {
                    await UpdateOrdersAsync(sinv_Sale_Outbound_Details);
                }
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 增加销售明细出库量，减少商品库存，修改销售订单出库状态
        /// </summary>
        /// <param name="sale_Outbound"></param>
        /// <param name="sinv_Sale_Outbound_Details"></param>
        /// <returns></returns>
        private async Task UpdateInventoryAndOrdersAsync(Sinv_Sale_Outbound sale_Outbound, List<Sinv_Sale_Outbound_Details> sinv_Sale_Outbound_Details)
        {
            // 聚合待更新数据
            var detailIds = sinv_Sale_Outbound_Details.Select(d => d.Sale_order_details_id).Distinct().ToList();
            var proCodes = sinv_Sale_Outbound_Details.Select(d => d.Pro_code).Distinct().ToList();
            var locationCodes = sinv_Sale_Outbound_Details.Select(d => d.Location_code).Distinct().ToList();
            var stockList = await myDbContext.inv_stock
                .Where(s => proCodes.Contains(s.pro_code)
                    && sale_Outbound.Warehouse_code.Contains(s.Warehouse_Code)
                    && sale_Outbound.Zone_code.Contains(s.Zone_Code)
                    && locationCodes.Contains(s.Location_Code))
                .ToListAsync();
            // 批量预加载（解决N+1查询）
            //var stocks = await myDbContext.inv_stock
            //    .Where(s => proCodes.Contains(s.pro_code))
            //    .ToDictionaryAsync(s => s.pro_code);

            var orderDetails = await myDbContext.Sinv_Sale_Order_Details
                .Where(sod => detailIds.Contains(sod.Sale_order_details_id))
                .ToDictionaryAsync(sod => sod.Sale_order_details_id);

            // 字典1：以stock_id为键
            var stocksById = stockList.ToDictionary(s => s.stock_id);
            // 字典2：以pro_code为键映射到stock_id
            var stockIdByProCode = stockList.ToDictionary(s => (s.pro_code, s.Location_Code), s => s.stock_id);
            
            foreach (var item in sinv_Sale_Outbound_Details)
            {
                if (stockIdByProCode.TryGetValue((item.Pro_code, item.Location_code), out var stockId))
                {
                    //减少预计出库数量
                    stocksById[stockId].Stock_planned_outbound_qty -= item.Pro_current_shipment_qty;
                    //减少库存数量
                    stocksById[stockId].stock_numder -= item.Pro_current_shipment_qty;
                    myDbContext.Entry(stocksById[stockId]).State = EntityState.Modified;
                }
            }
            // 扣减库存（带校验与并发控制）
            //foreach (var item in sinv_Sale_Outbound_Details)
            //{
            //    if (!stocks.TryGetValue(item.Pro_code, out var stock) ||
            //        stock.stock_numder < item.Pro_current_shipment_qty)
            //    {
            //        throw new Exception($"库存不足: {item.Pro_code}");
            //    }
            //    // 原子更新规避并发冲突
            //    stock.stock_numder -= item.Pro_current_shipment_qty;
            //    stock.Stock_planned_outbound_qty -= item.Pro_current_shipment_qty;
            //}

            // 更新明细出库量
            foreach (var item in sinv_Sale_Outbound_Details)
            {
                orderDetails[item.Sale_order_details_id].Pro_outbound_qty
                    += item.Pro_current_shipment_qty;
                orderDetails[item.Sale_order_details_id].Pro_planned_outbound_qty
                    -= item.Pro_current_shipment_qty;
            }

            //修改订单状态
            var order = await myDbContext.Sinv_Sale_Order
                .FirstAsync(so => so.Sale_order_code == sale_Outbound.Sale_order_code);
            order.Sale_order_status = sale_Outbound.Sale_outbound_status;
        }

        /// <summary>
        /// 条件查询销售出库总数
        /// </summary>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OutboundCountAsync(string customerName, string orderCode, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Outbound> query = myDbContext.Sinv_Sale_Outbound;
            query = query.Where(so => so.Del_flag == '0');
            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(so => so.Customer_code.Contains(customerName) || so.Customer_name.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(so => so.Sale_order_code.Contains(orderCode));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_outbound_status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_outbound_audit_status == auditStatus);
            }
            return await query.CountAsync();
        }

        /// <summary>
        /// 逻辑删除销售出库信息并修改销售订单明细的预计出库数量
        /// </summary>
        /// <param name="sinv_Sale_Outbound"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OutboundDelAsync(Sinv_Sale_Outbound sinv_Sale_Outbound)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售出库订单逻辑删除状态
                Sinv_Sale_Outbound sinv_Sale_Outbound1 = await myDbContext.Sinv_Sale_Outbound
                    .FirstOrDefaultAsync(so => so.Sale_outbound_id == sinv_Sale_Outbound.Sale_outbound_id);
                sinv_Sale_Outbound1.Del_flag = sinv_Sale_Outbound.Del_flag;
                myDbContext.Update(sinv_Sale_Outbound1);

                //更新销售明细预计出库数量
                List<Sinv_Sale_Outbound_Details> sinv_Sale_Outbound_Details = await myDbContext.Sinv_Sale_Outbound_Details
                    .Where(sod => sod.Sale_outbound_id == sinv_Sale_Outbound.Sale_outbound_id).ToListAsync();

                await UpdateOrdersAsync(sinv_Sale_Outbound_Details);

                await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 减少销售明细预计出库数量
        /// </summary>
        /// <param name="sinv_Sale_Outbound_Details"></param>
        /// <returns></returns>
        private async Task UpdateOrdersAsync(List<Sinv_Sale_Outbound_Details> sinv_Sale_Outbound_Details)
        {
            var netChangeDict = new Dictionary<int, decimal>();
            foreach (var delItem in sinv_Sale_Outbound_Details)
            {
                if (!netChangeDict.ContainsKey(delItem.Sale_order_details_id))
                    netChangeDict[delItem.Sale_order_details_id] = 0;
                netChangeDict[delItem.Sale_order_details_id] -= delItem.Pro_current_shipment_qty;
            }

            foreach (var (orderDetailId, netChange) in netChangeDict)
            {
                var orderDetail = await myDbContext.Sinv_Sale_Order_Details
                    .FirstAsync(sod => sod.Sale_order_details_id == orderDetailId);

                orderDetail.Pro_planned_outbound_qty += netChange; // 更新累计出库量
            }
        }

        /// <summary>
        /// 修改销售出库及其明细
        /// </summary>
        /// <param name="sinv_Sale_Outbound"></param>
        /// <param name="newDetails"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OutboundUpdateAsync(Sinv_Sale_Outbound sinv_Sale_Outbound, List<Sinv_Sale_Outbound_Details> newDetails)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //更新销售出库信息
                var saleOutbound = await myDbContext.Sinv_Sale_Outbound.FirstOrDefaultAsync(so => so.Sale_outbound_id == sinv_Sale_Outbound.Sale_outbound_id);
                saleOutbound.Sale_outbound_code = sinv_Sale_Outbound.Sale_outbound_code;
                saleOutbound.Sale_order_name = sinv_Sale_Outbound.Sale_order_name;
                saleOutbound.Sale_order_code = sinv_Sale_Outbound.Sale_order_code;
                saleOutbound.Customer_name = sinv_Sale_Outbound.Customer_name;
                saleOutbound.Customer_code = sinv_Sale_Outbound.Customer_code;
                saleOutbound.Contacts_name = sinv_Sale_Outbound.Contacts_name;
                saleOutbound.Contacts_phone = sinv_Sale_Outbound.Contacts_phone;
                saleOutbound.Sale_order_rep_id = sinv_Sale_Outbound.Sale_order_rep_id;
                saleOutbound.Sale_order_dept_id = sinv_Sale_Outbound.Sale_order_dept_id;
                saleOutbound.Sale_outbound_rep_id = sinv_Sale_Outbound.Sale_outbound_rep_id;
                saleOutbound.Sale_outbound_status = sinv_Sale_Outbound.Sale_outbound_status;
                saleOutbound.Sale_outbound_time = sinv_Sale_Outbound.Sale_outbound_time;
                saleOutbound.Sale_outbound_dept_id = sinv_Sale_Outbound.Sale_outbound_dept_id;
                saleOutbound.Warehouse_code = sinv_Sale_Outbound.Warehouse_code;
                saleOutbound.Warehouse_name = sinv_Sale_Outbound.Warehouse_name;
                saleOutbound.Zone_code = sinv_Sale_Outbound.Zone_code;
                saleOutbound.Zone_name = sinv_Sale_Outbound.Zone_name;
                saleOutbound.Update_by = sinv_Sale_Outbound.Update_by;
                saleOutbound.Update_time = sinv_Sale_Outbound.Update_time;
                myDbContext.Update(saleOutbound);
                await myDbContext.SaveChangesAsync();

                //查询数据库中的旧销售出库明细
                var oldDetails = await myDbContext.Sinv_Sale_Outbound_Details
                    .AsNoTracking()
                    .Where(sod => sod.Sale_outbound_code == sinv_Sale_Outbound.Sale_outbound_code)
                    .ToListAsync();

                //识别三类记录
                var toAdd = new List<Sinv_Sale_Outbound_Details>();//新增明细
                var toUpdate = new List<Sinv_Sale_Outbound_Details>();//更新明细
                var toDel = new List<int>();//删除明细id
                var netChangeDict = new Dictionary<int, decimal>(); // <sale_order_details_id, 净变化量>

                foreach (var newItem in newDetails)
                {
                    //新记录：无主键或主键不在旧列表中
                    if (newItem.Sale_outbound_details_id == 0 ||
                        !oldDetails.Any(old => old.Sale_outbound_details_id == newItem.Sale_outbound_details_id))
                    {
                        toAdd.Add(newItem);
                    }
                    else
                    {
                        var oldItem = oldDetails.First(old => old.Sale_outbound_details_id == newItem.Sale_outbound_details_id);
                        if (IsModified(oldItem, newItem))//检查字段是否有变化
                        {
                            toUpdate.Add(newItem);
                        }
                    }
                }

                // 处理删除的明细：减少出库量
                foreach (var delItem in oldDetails.Where(d => toDel.Contains(d.Sale_outbound_details_id)))
                {
                    if (!netChangeDict.ContainsKey(delItem.Sale_order_details_id))
                        netChangeDict[delItem.Sale_order_details_id] = 0;
                    netChangeDict[delItem.Sale_order_details_id] -= delItem.Pro_current_shipment_qty;
                }

                // 处理新增明细：增加出库量
                foreach (var newItem in toAdd)
                {
                    if (!netChangeDict.ContainsKey(newItem.Sale_order_details_id))
                        netChangeDict[newItem.Sale_order_details_id] = 0;
                    netChangeDict[newItem.Sale_order_details_id] += newItem.Pro_current_shipment_qty;
                }

                // 处理修改的明细：计算新旧差值
                foreach (var updateItem in toUpdate)
                {
                    var oldQty = oldDetails
                        .FirstOrDefault(old => old.Sale_outbound_details_id == updateItem.Sale_outbound_details_id)?
                        .Pro_current_shipment_qty ?? 0;

                    if (!netChangeDict.ContainsKey(updateItem.Sale_order_details_id))
                        netChangeDict[updateItem.Sale_order_details_id] = 0;

                    netChangeDict[updateItem.Sale_order_details_id] += updateItem.Pro_current_shipment_qty - oldQty;
                }


                toDel = oldDetails.Where(old => !newDetails.Any(newItem => newItem.Sale_outbound_details_id == old.Sale_outbound_details_id))
                    .Select(old => old.Sale_outbound_details_id).ToList(); // 错误：使用错误ID字段

                // 批量删除旧明细
                if (toDel.Any())
                {
                    var delItems = oldDetails.Where(d => toDel.Contains(d.Sale_outbound_details_id));
                    myDbContext.RemoveRange(delItems);
                }

                //更新变化的明细
                foreach (var item in toAdd)
                {
                    item.Sale_outbound_code = sinv_Sale_Outbound.Sale_outbound_code;
                    item.Sale_outbound_id = sinv_Sale_Outbound.Sale_outbound_id;
                    await myDbContext.AddAsync(item);
                }

                foreach (var updateItem in toUpdate)
                {
                    var existingDetail = oldDetails.FirstOrDefault(d => d.Sale_outbound_details_id == updateItem.Sale_outbound_details_id);
                    if (existingDetail != null)
                    {
                        existingDetail.Pro_awaiting_dispatch_qty = updateItem.Pro_awaiting_dispatch_qty;
                        existingDetail.Pro_current_shipment_qty = updateItem.Pro_current_shipment_qty;
                        existingDetail.Location_code = updateItem.Location_code;
                        existingDetail.Location_name = updateItem.Location_name;
                        myDbContext.Update(existingDetail);
                    }
                }

                await myDbContext.SaveChangesAsync();

                //更新库存预计出库数量
                //var proCodes = newDetails.Select(d => d.Pro_code).Distinct().ToList();
                //var locationCodes = newDetails.Select(d => d.Location_code).Distinct().ToList();
                //var stockList = await myDbContext.inv_stock
                //    .Where(s => proCodes.Contains(s.pro_code)
                //        && locationCodes.Contains(s.Location_Code)
                //        && saleOutbound.Warehouse_code.Contains(s.Warehouse_Code)
                //        && saleOutbound.Zone_code.Contains(s.Zone_Code))
                //    .ToListAsync();

                //// 字典1：以stock_id为键
                //var stocksById = stockList.ToDictionary(s => s.stock_id);
                //// 字典2：以pro_code为键映射到stock_id
                //var stockIdByCompositeKey = stockList.ToDictionary(
                //    s => $"{s.pro_code}_{s.Location_Code}",
                //    s => s.stock_id
                //);

                foreach (var (orderDetailId, netChange) in netChangeDict)
                {
                    var orderDetail = await myDbContext.Sinv_Sale_Order_Details
                        .FirstAsync(sod => sod.Sale_order_details_id == orderDetailId);

                    orderDetail.Pro_planned_outbound_qty += netChange; // 更新累计出库量
                }
                await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 检查字段是否被修改
        /// </summary>
        /// <param name="oldItem"></param>
        /// <param name="newItem"></param>
        /// <returns></returns>
        private bool IsModified(Sinv_Sale_Outbound_Details oldItem, Sinv_Sale_Outbound_Details newItem)
        {
            return oldItem.Pro_awaiting_dispatch_qty != newItem.Pro_awaiting_dispatch_qty ||
                   oldItem.Pro_current_shipment_qty != newItem.Pro_current_shipment_qty ||
                   oldItem.Location_code != newItem.Location_code ||
                   oldItem.Location_name != newItem.Location_name ||
                   oldItem.Sale_outbound_details_id == newItem.Sale_outbound_details_id;
        }
    }
}
